const { resolve } = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsWebpackPlugin =require('optimize-css-assets-webpack-plugin')

const commonCssLoader=[
    MiniCssExtractPlugin.loader,
    "css-loader",
    {
      // 还要在pakeage.json 定义browserslist
      loader:'postcss-loader',
      options:{
        postcssOptions:{
          ident:'postcss',
          plugins:[require('postcss-preset-env')()]
        },  
      }
    }
]
module.exports={
  entry:'./src/js/index.js',
  output:{
    filename:'js/built.js',
    path:resolve(__dirname,'build'),
    publicPath:'./'
  },
  module:{
    rules:[
        {
          test:/\.css$/,
          use:[
            // "style-loader",
            ...commonCssLoader
          ]
        },
        {
          test:/\.less$/,
          use:[
            ...commonCssLoader,
            "less-loader"
          ]
        },
        /**
         * 正常 一个文件只被一个loader执行，
         * 当一个文件需要被多个loader执行，一定要搞清楚loader先后顺序,
         * 先执行eslint,再执行babel
         */
        {
          test:/\.js$/,
          exclude:/node_modules/,
          enforce:'pre',// 优先执行
          loader:'eslint-loader',
          options:{
            fix:true
          }
        },
        {
          test:/\.js$/,
          exclude:/node_modules/,
          loader:'babel-loader',
          options:{
            presets:[
              [
                '@babel/preset-env',
                  {
                    useBuiltIns:'usage',
                    corejs:{
                      version:3,
                      targets:{
                        chrome:'60',
                        firefox:'50'
                      }
                    }
                  }
              ]
             
            ]
          }
        },
        {
          test:/\.(jpg|png|gif)$/,
          loader:'url-loader',
          options:{
            limit:10240,
            name:'[hash:10].[ext]',
            outputPath:'imgs'
          }
        },
        {
          test:/\.html$/,
          loader:'html-loader'
        },
        {
          exclude:/\.(js|html|css|less|png|jpg|gif)$/,
          loader:'file-loader',
          options:{
            outputPath:'media'
          },
        }
    ]
  },
  plugins:[
    new HtmlWebpackPlugin({
      template:'./src/index.html',
      minify:{
        collapseWhitespace:true,
        removeComments:true
      },
    }),
    new MiniCssExtractPlugin({
      filename:'css/built.css'
    }),
    // 压缩css
    new OptimizeCssAssetsWebpackPlugin()
  ],
  mode:'production'
}